<div class="panel panel-default panel-intro">
    <div class="panel-heading">
        {:build_heading(null,FALSE)}
        <ul class="nav nav-tabs">
            <li class="active"><a href="#edit" data-toggle="tab">{:__('编辑销售单')}</a></li>
        </ul>
    </div>
    <div class="panel-body">
        <div id="myTabContent" class="tab-content">
            <div class="tab-pane fade active in" id="edit">
                <div class="widget-body no-padding">
                    <form id="edit-form" class="form-horizontal" role="form" data-toggle="validator" method="POST" action="">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="control-label col-xs-12 col-sm-3">{:__('Manufacturer')}:</label>
                                    <div class="col-xs-12 col-sm-8">
                                        <input id="c-manufacturer_id" data-rule="required" data-source="manufacturer/index" class="form-control selectpage" name="row[manufacturer_id]" type="text" value="{$row.manufacturer_id}">
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="control-label col-xs-12 col-sm-3">{:__('Customer')}:</label>
                                    <div class="col-xs-12 col-sm-8">
                                        <input id="c-customer_id" data-rule="required" data-source="customer/index" class="form-control selectpage" name="row[customer_id]" type="text" value="{$row.customer_id}">
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="control-label col-xs-12 col-sm-3">{:__('Order_date')}:</label>
                                    <div class="col-xs-12 col-sm-8">
                                        <input id="c-order_date" class="form-control datetimepicker" data-date-format="YYYY-MM-DD HH:mm:ss" data-use-current="true" name="row[order_date]" type="text" value="{$row.order_date_text|htmlentities}">
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="control-label col-xs-12 col-sm-3">{:__('Discount_amount')}:</label>
                                    <div class="col-xs-12 col-sm-8">
                                        <input id="c-discount_amount" class="form-control" name="row[discount_amount]" type="number" value="{$row.discount_amount}" step="0.01" onchange="calculateTotalAmount()">
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label class="control-label col-xs-12 col-sm-2">{:__('商品明细')}:</label>
                                    <div class="col-xs-12 col-sm-9">
                                        <div class="table-responsive">
                                            <table class="table table-striped">
                                                <thead>
                                                    <tr>
                                                        <th>{:__('Product')}</th>
                                                        <th>{:__('Unit_price')}</th>
                                                        <th>{:__('Quantity')}</th>
                                                        <th>{:__('Jin_per_bag')}</th>
                                                        <th>{:__('Bags_per_piece')}</th>
                                                        <th>{:__('Purchase_price')}</th>
                                                        <th>{:__('Subtotal')}</th>
                                                        <th>{:__('操作')}</th>
                                                    </tr>
                                                </thead>
                                                <tbody id="item-list">
                                                    <tr id="item-template" class="item-row">
                                                        <td>
                                                            <input class="form-control product-select" data-rule="required" data-source="product/index" name="items[__index__][product_id]" type="text" value="">
                                                        </td>
                                                        <td><input class="form-control item-unit-price" name="items[__index__][unit_price]" type="number" value="0" step="0.01" onchange="calculateSubtotal(this)"></td>
                                                        <td><input class="form-control item-quantity" name="items[__index__][quantity]" type="number" value="1" min="1" onchange="calculateSubtotal(this)"></td>
                                                        <td><input class="form-control item-jin-per-bag" name="items[__index__][jin_per_bag]" type="number" value="0" step="0.01"></td>
                                                        <td><input class="form-control item-bags-per-piece" name="items[__index__][bags_per_piece]" type="number" value="0" step="0.01"></td>
                                                        <td><input class="form-control item-purchase-price" name="items[__index__][purchase_price]" type="number" value="0" step="0.01"></td>
                                                        <td class="item-subtotal">0.00</td>
                                                        <td><a href="javascript:;" class="btn btn-xs btn-danger btn-remove-item"><i class="fa fa-trash"></i></a></td>
                                                    </tr>
                                                </tbody>
                                                <tfoot>
                                                    <tr>
                                                        <td colspan="8">
                                                            <a href="javascript:;" class="btn btn-success btn-add-item"><i class="fa fa-plus"></i> {:__('添加商品')}</a>
                                                        </td>
                                                    </tr>
                                                </tfoot>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="control-label col-xs-12 col-sm-3">{:__('Total_weight')}:</label>
                                    <div class="col-xs-12 col-sm-8">
                                        <input id="c-total_weight" class="form-control" name="row[total_weight]" type="number" value="{$row.total_weight}" step="0.01" readonly>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="control-label col-xs-12 col-sm-3">{:__('Total_amount')}:</label>
                                    <div class="col-xs-12 col-sm-8">
                                        <input id="c-total_amount" class="form-control" name="row[total_amount]" type="number" value="{$row.total_amount}" step="0.01" readonly>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="control-label col-xs-12 col-sm-3">{:__('Total_purchase_price')}:</label>
                                    <div class="col-xs-12 col-sm-8">
                                        <input id="c-total_purchase_price" class="form-control" name="row[total_purchase_price]" type="number" value="{$row.total_purchase_price}" step="0.01" readonly>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="control-label col-xs-12 col-sm-3">{:__('Customer_payment')}:</label>
                                    <div class="col-xs-12 col-sm-8">
                                        <input id="c-customer_payment" class="form-control" name="row[customer_payment]" type="number" value="{$row.customer_payment}" step="0.01">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="control-label col-xs-12 col-sm-3">{:__('Manufacturer_payment')}:</label>
                                    <div class="col-xs-12 col-sm-8">
                                        <input id="c-manufacturer_payment" class="form-control" name="row[manufacturer_payment]" type="number" value="{$row.manufacturer_payment}" step="0.01">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="control-label col-xs-12 col-sm-3">{:__('Notes')}:</label>
                                    <div class="col-xs-12 col-sm-8">
                                        <textarea id="c-notes" class="form-control" name="row[notes]" rows="2">{$row.notes}</textarea>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group layer-footer">
                            <label class="control-label col-xs-12 col-sm-2"></label>
                            <div class="col-xs-12 col-sm-8">
                                <button type="submit" class="btn btn-success btn-embossed disabled">{:__('OK')}</button>
                                <button type="reset" class="btn btn-default btn-embossed">{:__('Reset')}</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    // 商品行模板索引
    var itemIndex = 0;
    
    // 初始化页面
    $(document).ready(function() {
        // 隐藏模板行
        $('#item-template').hide();
        
        // 加载已有商品项
        loadItems();
        
        // 绑定添加商品按钮事件
        $('.btn-add-item').click(function() {
            addItem();
        });
        
        // 绑定删除商品按钮事件 (使用事件委托)
        $('#item-list').on('click', '.btn-remove-item', function() {
            // 至少保留一行商品
            if ($('.item-row:visible').length > 1) {
                $(this).closest('tr').remove();
                calculateTotals();
            } else {
                Toastr.error('至少需要一个商品项');
            }
        });
    });
    
    // 加载已有商品项
    function loadItems() {
        // 获取页面中的商品数据
        var items = {:json_encode($items)|raw};
        
        if (items && items.length > 0) {
            // 遍历商品项
            $.each(items, function(index, item) {
                // 添加商品行
                var newRow = $('#item-template').clone();
                newRow.removeAttr('id').show();
                
                // 更新索引
                updateRowIndex(newRow, itemIndex++);
                
                // 设置商品数据
                newRow.find('.product-select').val(item.product_id).data('value', item.product_id);
                newRow.find('.item-unit-price').val(item.unit_price);
                newRow.find('.item-quantity').val(item.quantity);
                newRow.find('.item-jin-per-bag').val(item.jin_per_bag);
                newRow.find('.item-bags-per-piece').val(item.bags_per_piece);
                newRow.find('.item-purchase-price').val(item.purchase_price);
                newRow.find('.item-subtotal').text((item.unit_price * item.quantity).toFixed(2));
                
                // 添加到列表
                $('#item-list').append(newRow);
                
                // 初始化selectpage
                initSelectPage(newRow.find('.product-select'));
            });
        } else {
            // 如果没有商品项，添加一个空行
            addItem();
        }
        
        // 重新计算总计
        calculateTotals();
    }
    
    // 添加商品行
    function addItem() {
        // 克隆模板行
        var newRow = $('#item-template').clone();
        newRow.removeAttr('id').show();
        
        // 更新索引
        updateRowIndex(newRow, itemIndex++);
        
        // 添加到列表
        $('#item-list').append(newRow);
        
        // 初始化selectpage
        initSelectPage(newRow.find('.product-select'));
    }
    
    // 初始化SelectPage
    function initSelectPage(element) {
        element.selectPage({
            eAjaxSuccess: function(data) {
                return data;
            },
            eSelect: function(data) {
                if (data && data.id) {
                    var row = $(this.input).closest('tr');
                    
                    // 通过AJAX获取商品详细信息
                    $.ajax({
                        url: 'product/index',
                        type: 'get',
                        dataType: 'json',
                        data: {
                            ids: data.id
                        },
                        success: function(res) {
                            if (res && res.rows && res.rows.length > 0) {
                                var product = res.rows[0];
                                
                                // 自动填充商品信息
                                row.find('.item-unit-price').val(product.unit_price);
                                row.find('.item-jin-per-bag').val(product.jin_per_bag);
                                row.find('.item-bags-per-piece').val(product.bags_per_piece);
                                row.find('.item-purchase-price').val(product.unit_price * 0.8); // 默认进货价为单价的80%
                                
                                // 重新计算小计和总计
                                calculateSubtotal(row.find('.item-unit-price')[0]);
                            }
                        }
                    });
                }
            }
        });
    }
    
    // 更新行索引
    function updateRowIndex(row, index) {
        row.find('input').each(function() {
            var name = $(this).attr('name');
            if (name) {
                $(this).attr('name', name.replace('__index__', index));
            }
        });
    }
    
    // 计算小计
    function calculateSubtotal(element) {
        var row = $(element).closest('tr');
        var unitPrice = parseFloat(row.find('.item-unit-price').val()) || 0;
        var quantity = parseInt(row.find('.item-quantity').val()) || 0;
        var subtotal = unitPrice * quantity;
        
        // 更新小计显示
        row.find('.item-subtotal').text(subtotal.toFixed(2));
        
        // 重新计算总计
        calculateTotals();
    }
    
    // 计算所有总计
    function calculateTotals() {
        var totalAmount = 0;
        var totalWeight = 0;
        var totalPurchasePrice = 0;
        
        // 遍历所有商品行
        $('.item-row:visible').each(function() {
            var unitPrice = parseFloat($(this).find('.item-unit-price').val()) || 0;
            var quantity = parseInt($(this).find('.item-quantity').val()) || 0;
            var jinPerBag = parseFloat($(this).find('.item-jin-per-bag').val()) || 0;
            var bagsPerPiece = parseFloat($(this).find('.item-bags-per-piece').val()) || 0;
            var purchasePrice = parseFloat($(this).find('.item-purchase-price').val()) || 0;
            
            // 计算商品总金额
            totalAmount += unitPrice * quantity;
            
            // 计算商品总重量
            totalWeight += jinPerBag * bagsPerPiece * quantity;
            
            // 计算总进货价
            totalPurchasePrice += purchasePrice * quantity;
        });
        
        // 更新总金额和总重量显示
        $('#c-total_weight').val(totalWeight.toFixed(2));
        
        // 应用优惠金额
        calculateTotalAmount();
        
        // 更新总进货价
        $('#c-total_purchase_price').val(totalPurchasePrice.toFixed(2));
    }
    
    // 计算总金额（应用优惠）
    function calculateTotalAmount() {
        var totalAmount = 0;
        
        // 计算商品总金额
        $('.item-row:visible').each(function() {
            var unitPrice = parseFloat($(this).find('.item-unit-price').val()) || 0;
            var quantity = parseInt($(this).find('.item-quantity').val()) || 0;
            totalAmount += unitPrice * quantity;
        });
        
        // 应用优惠金额
        var discountAmount = parseFloat($('#c-discount_amount').val()) || 0;
        totalAmount = Math.max(0, totalAmount - discountAmount);
        
        // 更新总金额
        $('#c-total_amount').val(totalAmount.toFixed(2));
    }
</script> 